package org.rainwalk.bill.service.impl;

import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.rainwalk.bill.entity.Token;
import org.rainwalk.bill.service.IMailService;
import org.rainwalk.bill.util.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

/**
 * 邮件服务实现
 *
 * @author 趁雨行
 */
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
//@ConditionalOnProperty(name = "spring.mail.enable", havingValue = "true")
public class MailServiceImpl implements IMailService {

    private final JavaMailSenderImpl mailSender;

    @Value("${spring.mail.username}")
    private String fromMailAddress;

    @Value("${spring.mail.login-notify-address}")
    private String loginNotifyAddress;

    @Value("${spring.mail.error-notify-address}")
    private String errorNotifyAddress;

    @Async
    @Override
    public void loginNotify(Token token) {
        String[] receivers = loginNotifyAddress.split(",");
        if (receivers.length == 0) {
            return;
        }

        String userId = token.getUserId();
        String ip = token.getIp();

        String address = "";
        if (StrUtil.isNotBlank(ip)) {
            //响应例子 var lo="广东省", lc="深圳市"; var localAddress={city:"深圳市", province:"广东省"}
            try {
                String ipResult = HttpUtil.get("http://ip.ws.126.net/ipquery?ip=" + ip);
                String city = ipResult.substring(ipResult.indexOf("city:") + 6, ipResult.indexOf("province") - 3);
                String province = ipResult.substring(ipResult.indexOf("province:") + 10, ipResult.indexOf("\"}"));
                address = province + city;
            } catch (Exception e) {
                log.error("查询ip[{}]地址失败 <===> {}", ip, ExceptionUtil.stacktraceToString(e));
            }
        }
        String title = "懒人账单-用户登录通知";
        String content = String.format("登录用户：id[%s] \n登录ip：%s \n 登录时间：%s \n 登录地址：%s",
                userId, ip, TimeUtil.formatTimestamp(token.getRefreshTime(), "yyyy-MM-dd HH:mm:ss"), address);
        for (String receiver : receivers) {
            sendSimpleMail(receiver, title, content);
        }
    }

    @Async
    @Override
    public void errorNotify(Throwable throwable) {
        String[] receivers = errorNotifyAddress.split(",");
        if (receivers.length == 0) {
            return;
        }
        String title = "懒人账单-应用错误通知";
        String content = String.format("错误信息：%s", ExceptionUtil.stacktraceToString(throwable));
        for (String receiver : receivers) {
            sendSimpleMail(receiver, title, content);
        }
    }

    /**
     * 发送简单邮件
     *
     * @return 发送成功返回 true
     */
    private void sendSimpleMail(String receiver, String title, String content) {
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setFrom(fromMailAddress);
        simpleMailMessage.setTo(receiver);
        simpleMailMessage.setSubject(title);
        simpleMailMessage.setText(content);
        try {
            mailSender.send(simpleMailMessage);
        } catch (MailException e) {
            log.error("邮件[{}]发送失败, 原因：{}", simpleMailMessage, ExceptionUtil.stacktraceToString(e));
        }
    }
}
